package api

import (
	"cs/models"
	"cs/request"
	"cs/ws"
	"encoding/json"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

func GetMessages(c *gin.Context) {
	conversation_id, _ := strconv.Atoi(c.Query("conversation_id"))
	page_size, _ := strconv.Atoi(c.Query("page_size"))
	page_num, _ := strconv.Atoi(c.Query("page_num"))

	data, total, err := models.FindMessage(conversation_id, page_num, page_size)
	if err == nil {
		c.JSON(http.StatusOK, gin.H{"status": "success", "messages": data, "total": total})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "messages": err.Error()})
	}
}

func AddMessage(c *gin.Context) {
	var form request.AddMessageForm
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数验证失败"})
		return
	}
	message := models.Message{
		Content:        form.Content,
		Type:           form.Type,
		Sender:         form.Sender,
		Receiver:       form.Receiver,
		From:           form.From,
		ConversationId: form.ConversationId,
	}
	if err := models.AddMessage(message); err != nil {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
		return
	}
	//用户在线的话将消息推送给用户
	if ws.IsOnline(form.Receiver, form.ToRole) {
		payload, _ := json.Marshal(ws.Payload{
			Cmd:      "talk",
			Content:  form.Content,
			Type:     form.Type,
			Sender:   form.Sender,
			Receiver: form.Receiver,
			ToRole:   form.ToRole,
			ChatId:   form.ConversationId,
		})
		//将消息推送给目标用户
		ws.SendToRole(form.Receiver, form.ToRole, payload)
	}

	c.JSON(http.StatusOK, gin.H{"status": "success", "data": message})
}

func DeleteMessage(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	if err := models.DelMessage(id); err == nil {
		c.JSON(http.StatusOK, gin.H{"status": "success", "message": "ok"})
	} else {
		c.JSON(http.StatusOK, gin.H{"status": "failed", "message": err.Error()})
	}
}

func MarkAsRead(c *gin.Context) {
	var form request.MarkAsReadForm
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "参数验证失败"})
		return
	}
	if form.Owner == "user" {
		models.CleanUnread(form.ConversationId, "user_unread")
	} else {
		models.CleanUnread(form.ConversationId, "guest_unread")
	}

	c.JSON(200, gin.H{"status": "success", "message": "ok"})
}
